package treediff.wrapper;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.lang3.StringEscapeUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.lexer.Page;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import treediff.filter.MatchesWrap;
import wish.stages.ParsingStage;

public class TreeEditDistanceWrapper {

	private static final String NO_MATCHING_TAG = "DIV";

	private static final String ID_NO_MATCHING = "id";

	private static final String ID_NO_MATCHING_VALUE = "no_matching_tag";
	
	private TagNode node;
	private String path;
	private Integer level;

	public void extract(File wrap, File file, File outputFile) throws IOException, ParserException {
		
		readWrapper(wrap);
		
		String htmlContent = ParsingStage.readFile(file);
				
		Parser parser = new Parser(new Lexer(new Page(htmlContent, "UTF-8")));
		
		NodeList n = parser.parse(new MatchesWrap(level,path,node));

//		if (n.size() != 1){
//			System.out.println("HAVE BEEN FOUND: " + n.size());
//			if (n.size() > 1){
//				System.out.println(n.toHtml());
//			}
//		}
		
		writeOutput(n,outputFile);
		
	}

	private void writeOutput(NodeList n, File outputFile) throws IOException {
		BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
		
		bw.write("<h2>" + StringEscapeUtils.escapeHtml3(node.toHtml()) + "</h2>");
		
		for (int i = 0; i < n.size(); i++) {
			
			bw.write("<br><h2>Found</h2><br>");
			bw.write("<br>\n" + n.elementAt(i).toHtml());
			
		}
		
		bw.close();
		
	}

	private void readWrapper(File wrap) throws IOException, ParserException {
		
		BufferedReader br = new BufferedReader(new FileReader(wrap));
		
		level = Integer.valueOf(br.readLine().replace("LEVEL: ", ""));
		
		String nodeString = br.readLine().replace("NODE: ", "");
		
		int ind = nodeString.indexOf('<');

		if (ind < 0){
			
			node = new TagNode();
		
			node.setTagName(NO_MATCHING_TAG);
		
			node.setAttribute(ID_NO_MATCHING, ID_NO_MATCHING_VALUE);
			
		}else{

			
			path = nodeString.substring(0,ind);
			
			String nodeStr = nodeString.substring(ind);

			Parser parser = new Parser(new Lexer(new Page(nodeStr, "UTF-8")));
			
			NodeList nl = parser.parse(null);
			
			if (nl.elementAt(0) instanceof TagNode){
				node = (TagNode) nl.elementAt(0);

			}else{
				
				node = new TagNode();
				node.setTagName(NO_MATCHING_TAG);
			}
			
		}
		
		br.close();
		
	}

}
